package com.android.aconportable;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

//import org.xiph.speex.*;

//import javax.media.*;
//import org.xiph.speex.Bits;


public class OutComePacket {
	
	private UDPSocket socket;
	private boolean isRecording = false;
	static final int frequency = 8000;
	static final int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
	static final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
	private int recBufSize;
	private AudioRecord audioRecord;
	private int bufferReadResult = 0;
	static final int framesize = 1024;
	//private javax.media.Codec codec;
	//private org.xiph.speex.Bits bits;
	
	//private SpeexEncoder encoder;
	
	public OutComePacket(UDPSocket socket){
		this.socket = socket;
		//recBufSize = 480;
		recBufSize = AudioRecord.getMinBufferSize(frequency,channelConfiguration, audioEncoding);
		audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency,
				channelConfiguration, audioEncoding, recBufSize);
		
		System.out.println(recBufSize);
		//encoder = new SpeexEncoder();
		//encoder.init(1, 10, frequency, audioRecord.getChannelCount());
		
	}
	
	class OutComeThread extends Thread {
		public void run() {
			try {
				
				//bits = new org.xiph.speex.Bits();
				
				byte[] buf = new byte[recBufSize];
				//byte[] buf2 = new byte[480];
				//int offset = 0;
				//javax.media.Buffer buffer = new javax.media.Buffer();
				//javax.media.Buffer buffer2 = new javax.media.Buffer();
				
		
				audioRecord.startRecording();
				//track.play();
				//codec.setInputFormat(new Format(javax.media.format.AudioFormat.LINEAR, Format.byteArray));
				//codec.setOutputFormat(new Format(javax.media.format.AudioFormat.GSM_RTP, Format.byteArray));
				
				
				while (isRecording) {

					//bufferReadResult = audioRecord.read(buf, 0,recBufSize);
					bufferReadResult = audioRecord.read(buf, 0, framesize);

					
					socket.send(buf, bufferReadResult);
					
				}
				//
				//audioRecord.stop();
			} catch (Throwable t) {
				// Toast.makeText(context, t.getMessage(), 1000);
			}
		}
	};
	
	public void record(){
		stop();
		audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency,
				channelConfiguration, audioEncoding, recBufSize);
		isRecording = true;
		
		new OutComeThread().start();
	}
	
	public void stop(){
		if(audioRecord != null){
			isRecording = false;
			audioRecord.stop();
			audioRecord.release();
			audioRecord = null;
		}
		
		//audioRecord.release();
		//audioRecord = null;
	}
	
	public void finish(){
		if(audioRecord != null){
			audioRecord.release();
			audioRecord = null;
		}
	}
	
	


	

}
